package com.example.demo.controller;

import com.example.demo.entity.Privilege;
import com.example.demo.entity.UserDto;
import com.example.demo.mapper.UserMapper;
import com.example.demo.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class UseController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtil jwtUtil;
/*    {
        "username":"lisi",
        "password":"123456"
    }*/
    @PostMapping(value = "/login")
    public String login(@RequestBody UserDto userDto){
        String ret="invalid user";
        UserDto user = userMapper.getUserByUsername(userDto.getUsername());
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        boolean bmatch = bCryptPasswordEncoder.matches(userDto.getPassword(), user.getPassword());
        if(user!=null&&bmatch){
            List<Privilege> list= user.getPrivilege();
            String[] roles = list.stream().map(Privilege::getAuthority).toList().toArray(String[]::new);
            ret=jwtUtil.generateToken(userDto.getUsername(),roles);
        }
        return ret;

    }
    @RequestMapping("/admin/hello")
    public String sayHello(){
        return "hello";
    }
    @RequestMapping("/admin/go")
    public String go(){
        return "hello";
    }
}
